package com.mingqijia.gassafety.webserver.service.cmp.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentStatus;
import com.mingqijia.gassafety.webserver.dto.ReportNotifyDTO;
import com.mingqijia.gassafety.webserver.dto.ReportNotifyOfflineDTO;
import com.mingqijia.gassafety.webserver.request.cmp.notify.DataReportDataRequest;
import com.mingqijia.gassafety.webserver.request.cmp.notify.DataReportRequest;
import com.mingqijia.gassafety.webserver.service.ReceiverValveService;
import com.mingqijia.gassafety.webserver.service.RecordReceiverValveService;
import com.mingqijia.gassafety.webserver.service.cmp.AbstractCmpDataNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.*;


/**
 *  CMP平台告警（监测）上报回调具体实现
 *
 * @author zhufeng
 * @since 2022/8/4
 */
@Service
@Slf4j
public class CmpAlarmNotifyServiceImpl extends AbstractCmpDataNotifyService {

    @Autowired
    ReceiverValveService receiverValveService;
    @Autowired
    RecordReceiverValveService recordReceiverValveService;

    @Override
    protected DeviceState prepareDeviceState(DataReportRequest request, Dtu dtu) {
        DeviceState deviceState = new DeviceState();
        deviceState.setDeviceId(dtu.getId());
        deviceState.setDetectorCount(request.getDetectorNum());
        deviceState.setSpId(dtu.getSpId());
        return deviceState;
    }

    @Override
    protected RecordDetector prepareRecordDetector(DataReportDataRequest t, Dtu newDtu) {
        RecordDetector recordDetector = new RecordDetector();
        recordDetector.setDeviceId(newDtu.getId());
        recordDetector.setRecordId(t.getRecordId());
        recordDetector.setConsumerId(newDtu.getConsumerId());
        recordDetector.setRecordAt(t.getRecordAt());
        recordDetector.setSubId(t.getSno());
        recordDetector.setAlertType(t.getAlarmType());
        recordDetector.setGasType(t.getGasType());
        recordDetector.setConcentration(t.getConcentration());
        recordDetector.setTemperature(t.getTemperature());
        recordDetector.setHumidity(t.getHumidity());
        recordDetector.setSpId(t.getSpId());
        return recordDetector;
    }

    @Override
    protected void saveReceiverValve(DataReportRequest request, Dtu dtu, Long controllerId, ReportNotifyDTO notifyDTO, ReportNotifyOfflineDTO offlineDTO) {
        if (!Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom())) return;
        log.info("监测上报的电磁息记阀信录");
        ReceiverValve newReceiverValve = new ReceiverValve();
        LambdaQueryWrapper<ReceiverValve> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReceiverValve::getDeviceId,dtu.getIMEI());
        ReceiverValve receiverValve = receiverValveService.getOne(queryWrapper);
        //没有接收器和电磁阀并且上报状态是离线，则不做任何操作
        if (request.getValveConnection() == null || VALVE_CONNECTION_0.equals(request.getValveConnection()) &&
                (receiverValve == null || receiverValve.getIsDeleted().equals(1))) {
            log.info("没有接收器和电磁阀并且上报状态是离线，则不做任何操作");
            return;
        } else {
            newReceiverValve.setDeviceId(dtu.getIMEI());
            if (VALVE_CONNECTION_0.equals(request.getValveConnection())) {
                newReceiverValve.setReceiverStatus(RECEIVER_STATUS_OFFLINE);
            } else {
                newReceiverValve.setReceiverStatus(RECEIVER_STATUS_NORMAL);
                if (request.getValveConnection() > 1) {
                    newReceiverValve.setValveId(String.valueOf(request.getValveConnection()));
                }
            }
            //故障
            String valveStatusDesc = request.getValveStatusDesc() == null ? "":request.getValveStatusDesc();
            //接收器和电磁阀离线
            if (valveStatusDesc.contains(VALVE_BROKEN_STATUS_71.toString())) {
                newReceiverValve.setReceiverStatus(RECEIVER_STATUS_OFFLINE);
            }
            if (VALVE_WORK_STATUS_1.equals(request.getValveWorkStatus())) {
                newReceiverValve.setBrokenStatus(VALVE_WORK_STATUS_BROKEN);
                if (!StringUtils.isEmpty(valveStatusDesc)) {
                    //电池欠压
                    if (valveStatusDesc.contains(VALVE_BROKEN_STATUS_74.toString())) {
                        newReceiverValve.setBatteryStatus(BATTERY_STATUS_BROKEN);
                    }
                    String brokenStatusInfo = "";
                    if (valveStatusDesc.contains(VALVE_BROKEN_STATUS_70.toString())) {
                        brokenStatusInfo = VALVE_BROKEN_STATUS_70_INFO+";";
                    }
                    if (valveStatusDesc.contains(VALVE_BROKEN_STATUS_71.toString())) {
                        brokenStatusInfo = brokenStatusInfo + VALVE_BROKEN_STATUS_71_INFO+";";
                    }
                    if (valveStatusDesc.contains(VALVE_BROKEN_STATUS_72.toString())) {
                        brokenStatusInfo = brokenStatusInfo + VALVE_BROKEN_STATUS_72_INFO+";";
                    }
                    if (valveStatusDesc.contains(VALVE_BROKEN_STATUS_73.toString())) {
                        brokenStatusInfo = brokenStatusInfo + VALVE_BROKEN_STATUS_73_INFO+";";
                    }
                    newReceiverValve.setBrokenStatusInfo(brokenStatusInfo);
                }
            } else {
                newReceiverValve.setBrokenStatus(VALVE_WORK_STATUS_NORMAL);
                newReceiverValve.setBrokenStatusInfo("");
            }
            if (VALVE_STATUS_0.equals(request.getValveStatus())) {
                newReceiverValve.setValveStatus(VALVE_STATUS_OPEN);
            } else if(VALVE_STATUS_1.equals(request.getValveStatus())){
                newReceiverValve.setValveStatus(VALVE_STATUS_CLOSE);
            }
            newReceiverValve.setSpId(dtu.getSpId());
            if (receiverValve == null) {
                log.info("新增接收器和电磁阀状态更新表："+newReceiverValve.toString());
                receiverValveService.save(newReceiverValve);
            } else {
                if (!valveStatusDesc.contains(VALVE_BROKEN_STATUS_74.toString())) {
                    newReceiverValve.setBatteryStatus(BATTERY_STATUS_NORMAL);
                }
                newReceiverValve.setIsDeleted(0);
                if (receiverValve.getIsDeleted().equals(1)) {
                    newReceiverValve.setReceiverCode("");
                    newReceiverValve.setReceiverType("");
                    newReceiverValve.setReceiverPowerMode("");
                }
                newReceiverValve.setId(receiverValve.getId());
                log.info("更新接收器和电磁阀状态更新表："+newReceiverValve.toString());
                receiverValveService.updateById(newReceiverValve);
            }
            if (notifyDTO != null) {
                notifyDTO.setReceiverValve(receiverValve);
                notifyDTO.setPrepareReceiverValve(newReceiverValve);
            }
            if (offlineDTO != null) {
                offlineDTO.setReceiverValve(newReceiverValve);
            }
        }
        RecordReceiverValve recordReceiverValve = new RecordReceiverValve();
        recordReceiverValve.setRecordId(controllerId);
        recordReceiverValve.setDeviceId(dtu.getIMEI());
        if (VALVE_CONNECTION_0.equals(request.getValveConnection())) {
            recordReceiverValve.setReceiverStatus(RECEIVER_STATUS_OFFLINE);
        } else {
            recordReceiverValve.setReceiverStatus(RECEIVER_STATUS_NORMAL);
            if (request.getValveConnection() > 1) {
                recordReceiverValve.setValveId(String.valueOf(request.getValveConnection()));
            }
        }
        recordReceiverValve.setValveWorkStatus(request.getValveWorkStatus());
        recordReceiverValve.setValveStatus(request.getValveStatus());
        recordReceiverValve.setBrokenStatus(request.getValveStatusDesc());
        recordReceiverValve.setRecordAt(new Date());
        recordReceiverValve.setSpId(dtu.getSpId());
        log.info("新增接收器和电磁阀上报数据："+recordReceiverValve.toString());
        recordReceiverValveService.save(recordReceiverValve);
    }

    @Override
    protected DeviceState updateDeviceStateByDetector(DataReportDataRequest t, Dtu newDtu, Integer deviceStatus) {
        DeviceState deviceState = new DeviceState();
        deviceState.setDeviceId(newDtu.getId());
        //探测器有报警,优先更新报警状态
        //此前状态故障(DEVICE_STATUS_4),   alarmType = 0 & 3 不能修改状态
        DeviceState state = getStateByDeviceId(newDtu.getId(), newDtu.getSpId());
        //如果此前未上报过,预设状态为正常
        Integer statusOld = DEVICE_STATUS_1;
        Boolean isBroken = false;
        if(state != null){
            statusOld = state.getDeviceStatus();
            isBroken = state.getIsBroken();
        }
        if (ALARM_TYPE_LOW.equals(t.getAlarmType())){
            deviceState.setDeviceStatus(DEVICE_STATUS_2);
            deviceState.setDeviceStatusInfo(ALARM_TYPE_LOW_INFO);
        }else if (ALARM_TYPE_HIGH.equals(t.getAlarmType())){
            deviceState.setDeviceStatus(DEVICE_STATUS_3);
            deviceState.setDeviceStatusInfo(ALARM_TYPE_HIGH_INFO);
        }else if (ALARM_TYPE_RECOVERY.equals(t.getAlarmType()) &&  !DEVICE_STATUS_4.equals(statusOld)){
            deviceState.setDeviceStatus(DEVICE_STATUS_1);
            deviceState.setDeviceStatusInfo(ALARM_TYPE_RECOVERY_INFO);
            if (isBroken) {
                //故障->报警->报警恢复时触发的逻辑
                deviceState.setDeviceStatus(DEVICE_STATUS_4);
                deviceState.setDeviceStatusInfo(state.getBrokenStatusInfo());
            }
        }else if ( ALARM_TYPE_CHANGE.equals(t.getAlarmType())  &&  !DEVICE_STATUS_4.equals(statusOld)){
            //2023.11.5经钱慧凤和黄惠确认，变化监测不更新设备状态，只更新浓度值
//            deviceState.setDeviceStatus(DEVICE_STATUS_1);
//            deviceState.setDeviceStatusInfo(ALARM_TYPE_CHANGE_INFO);
        } else if ( ALARM_STATUS_1.equals(t.getAlarmStatus())){
            deviceState.setDeviceStatus(EquipmentStatus.alert);
            deviceState.setDeviceStatusInfo(ALARM_TYPE_ALERT_INFO);
        }
        deviceState.setConcentration(t.getConcentration());
        deviceState.setTemperature(t.getTemperature());
        deviceState.setHumidity(t.getHumidity());
        deviceState.setSpId(t.getSpId());
        return deviceState;
    }

    @Override
    protected RecordController prepareRecordController(DataReportRequest dataReportRequest, Dtu dtu) {
        RecordController recordController = new RecordController();
        recordController.setDeviceId(dtu.getId());
        recordController.setConsumerId(dtu.getConsumerId());
        recordController.setRecordType(dataReportRequest.getRecordType());
        recordController.setRecordAt(dataReportRequest.getReportDate());
        recordController.setValveTriggered(dataReportRequest.getValveControl());
        recordController.setDetectorCount(dataReportRequest.getDetectorNum());
        recordController.setSpId(dtu.getSpId());
        return recordController;
    }


}
